package com.dou.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dou.yygh.common.exception.YyghException;
import com.dou.yygh.common.helper.JWTHelper;
import com.dou.yygh.common.result.ResultCodeEnum;
import com.dou.yygh.enums.AuthStatusEnum;
import com.dou.yygh.model.user.Patient;
import com.dou.yygh.model.user.UserInfo;
import com.dou.yygh.user.mapper.UserInfoMapper;
import com.dou.yygh.user.service.PatientService;
import com.dou.yygh.user.service.UserInfoService;
import com.dou.yygh.vo.user.LoginVo;
import com.dou.yygh.vo.user.UserAuthVo;
import com.dou.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA 2021.1 x64
 *
 * @Author: 窦义超
 * @Date: 2021/09/2021/9/27/13:16
 * @Description:
 */
@Service
public class UserInfoServiceImpl extends
        ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;
    //用户手机号登录
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从loginVo获取手机号,和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断是否为空
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //TODO 判断是否一致

        //判断是否为第一次登录
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        if(userInfo==null){
            //第一次使用,添加
            userInfo=new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
        //校验是否被禁用
        if(userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //返回登录信息返回用户名
        //返回token信息
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);


        //jwt生成token字符串
        String token = JWTHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;

    }
    //用户认证提交
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证人的姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        //进行信息更新
        baseMapper.updateById(userInfo);
    }
    //用户列表("条件查询待分页")
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String keyword = userInfoQueryVo.getKeyword();      //用户名称
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();  //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)){
            wrapper.like("name",keyword);
        }
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)){
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            wrapper.ne("create_time",createTimeEnd);
        }
        //调用mapper犯法
        IPage<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应的值
        userInfoPage.getRecords().stream().forEach(item->{
            this.pageUserInfo(item);
        });
        return userInfoPage;
    }

    //用户锁定
    @Override
    public void lock(long userId, Integer status) {
        if(status.intValue()==0||status.intValue()==1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }
    //用户详情
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> map = new HashMap();
        //根据Userid查询用户信息
        UserInfo userInfo =this.pageUserInfo(baseMapper.selectById(userId)) ;
        map.put("userInfo",userInfo);
        //根据userid查询就诊人的信息
        List<Patient> allUserId = patientService.findAllUserId(userId);
        map.put("patientList",allUserId);
        return map;
    }
    //认证审批 2通过 -1不通过
    @Override
    public void approval(long userId, Integer authStatus) {
        if(authStatus.intValue()==2||authStatus.intValue()==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private UserInfo pageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }


}

